<?php
// 网络相关库

/**
 * 请求函数
 *
 * @param array $data
 * @param bool  $isJson
 * @return array|bool|string|null
 */
function request(array $data, bool $isJson = false)
{
    if (empty($data['method'])) {
        $data['method'] = 'GET';
    }
    if ($data['method'] == 'GET') {
        $resp = curlGet($data['url'], V($data, 'headers'), V($data, 'timeout'));
    } else {
        $resp = curlPost($data['url'], V($data, 'params'), V($data, 'headers'), V($data, 'timeout'), V($data, 'build'));
    }
    return ($isJson === true) ? (array)json_decode($resp, true) : $resp;
}

// curl post
function curlPost($url, $params, $headers = [], $timeout = 5, $build = true)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //设置超时
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_POST, true);
    if ($build) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    // 代理
    if(defined('PROSTATE') && PROSTATE){
        curl_setopt($ch, CURLOPT_PROXYTYPE, PROXYTYPE);
        curl_setopt($ch, CURLOPT_PROXY, PROXY);
        curl_setopt($ch, CURLOPT_PROXYPORT, PROXYPORT);
    }
    // https 请求
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    if ($error = curl_error($ch)) {
        die($error);
    }
    curl_close($ch);
    return $result;
}

function curlGet($url, $headers = null, $timeout = 5): bool|string
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 代理
    if(defined('PROSTATE') && PROSTATE){
        curl_setopt($ch, CURLOPT_PROXYTYPE, PROXYTYPE);
        curl_setopt($ch, CURLOPT_PROXY, PROXY);
        curl_setopt($ch, CURLOPT_PROXYPORT, PROXYPORT);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}


/*服务器之间数据交换*/
function curl($url, $data, $timeout = 10): bool|string
{
    $ch = curl_init();                              //初始化curl
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);    //设置超时（秒）
    curl_setopt($ch, CURLOPT_URL, $url);            //需要获取的URL地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_HEADER, false);        //启用时会将头文件的信息作为数据流输出。（因为是模拟post信息，所以不需要输出头文件）
    if (isset($data)) {
        curl_setopt($ch, CURLOPT_POST, true);        //启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //全部数据使用HTTP协议中的"POST"操作来发送。
    }
    $result = curl_exec($ch); //执行一个cURL会话
    curl_close($ch);          //关闭一个cURL会话并且释放所有资源。cURL句柄ch 也会被释放。
    //返回结果
    if ($result) {
        return $result;
    } else {
        return "curl出错:" . curl_errno($ch);
    }
}

/*获取ip地址*/
function getIp()
{
    $ip = '';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) {
            unset($arr[$pos]);
        }
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $num = sprintf("%u", ip2long($ip));
    if ($num > 0) {
        return $ip;
    } else {
        return $num;
    }
}

function ipAddress(): array
{
    $result['ip'] = getIp(); //当前IP
    $date         = date("Y-m-d");
    $time         = date("Y-m-d H:i:s");
    $ipArray      = query("ip", " ip = '$result[ip]' ");
    if (empty($ipArray['id'])) {
        $finger = 1;
    } else {
        if ($ipArray['date'] == $date) {
            $finger = 2;
        } else {
            $finger = 3;
        }
    }
    if (in_array($finger, array(1, 3))) {
        //获取ip地址信息
        $url               = "https://apis.map.qq.com/ws/location/v1/ip?ip=" . $result['ip'] . "&key=IE3BZ-FCI34-A2QU5-DVYWJ-OU5T5-KZFC5";
        $curl              = json_decode(curl($url, ""), true);
        $address           = $curl['result']['ad_info'];
        $result['address'] = $address['nation'] . "-" . $address['province'] . "-" . $address['city'] . "-" . $address['district'];
        //存入ip库
        if ($finger == 1) {
            insert(array("table" => "ip", "field" => array("ip" => $result['ip'], "address" => $result['address'], "date" => $date, "time" => $time)));
        } elseif ($finger == 3 and $result['address'] != "---") {
            update(array("table" => "ip", "field" => array("address" => $result['address'], "date" => $date), "where" => " id = '$ipArray[id]' "));
        }
    } else {
        $result['address'] = $ipArray['address'];
    }
    return $result;
}


/*判断客户设备函数*/
function isMobile(): bool
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return (bool)stristr($_SERVER['HTTP_VIA'], "wap");
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry',
            'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile',
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if (
            (str_contains($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml')) &&
            (!str_contains($_SERVER['HTTP_ACCEPT'], 'text/html') || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))
        ) {
            return true;
        }
    }
    return false;
}

/*判断是否为微信浏览器*/
function isWeixin(): bool
{
    if (str_contains($_SERVER['HTTP_USER_AGENT'], "MicroMessenger")) {
        return true;
    }
    return false;
}

/*发送验证短信
$data = array(
    "tel" => "接收短信的手机号码",
    "TemplateCode" => "短信模板ID",
    "TemplateParam" => "短信模板变量",
);
*/
function sms($data): bool|stdClass
{
    $params = [];
    //必填：是否启用https
    $security = false;
    //必填: 请参阅 https://ak-console.aliyun.com/取得你的AK信息
    $accessKeyId     = para("aliyunKey");
    $accessKeySecret = para("aliyunSecret");
    //必填:短信接收号码
    $params["PhoneNumbers"] = $data['tel'];
    //必填:短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
    $params["SignName"] = para("aliyunSign");
    //fixme必填:短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
    $params["TemplateCode"] = $data['TemplateCode'];
    //可选:设置模板参数, 假如模板中存在变量需要替换则为必填项
    $params['TemplateParam'] = $data['TemplateParam'];
    //可选:设置发送短信流水号
    $params['OutId'] = "666666";
    //可选:上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
    $params['SmsUpExtendCode'] = "1234567";
    //***需用户填写部分结束, 以下代码若无必要无需更改***//
    if (isset($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }
    //初始化SignatureHelper实例用于设置参数，签名以及发送请求
    require_once serverRoot . "interface/aliyun/SignatureHelper.php";
    $helper = new SignatureHelper();
    //此处可能会抛出异常，注意catch
    return $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, [
            "RegionId" => "cn-hangzhou",
            "Action"   => "SendSms",
            "Version"  => "2017-05-25",
        ]),
        $security
    );
}


/**
 * 获取微信的一些Token  oaAccessToken：企业微信OA-token/access_token:微信token
 */
function wechatToken($paid)
{
    $access_token = setWeChatToken($paid);
    if (empty($access_token)) {
        //获取access_token
        $url = '';
        switch ($paid) {
            case 'qyLoginToken':
                //企业微信扫码登录应用token
                $appid  = para("qyWeChatCorpid");
                $secret = para("qyWeChatLoginSecret");
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $appid . "&corpsecret=" . $secret;
                break;
            case 'access_token':
                //微信小程序token
                $appid  = para("wxOaAppid");
                $secret = para("wxOaAppSecret");
                $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
                break;
            case 'wechat_crm_token':
                //微信-crm
                $appid  = para("wxCrmAppid");
                $secret = para("wxCrmAppSecret");
                $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
                break;
            case 'oaAccessToken':
                //企业微信OA
                $appid  = para("qyWeChatCorpid");
                $secret = para("qyWeChatOaSecret");
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $appid . "&corpsecret=" . $secret;
                break;
            case 'crmAccessToken':
                //企业微信CRM
                $appid  = para("qyWeChatCorpid");
                $secret = para("qyWeChatCrmSecret");
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $appid . "&corpsecret=" . $secret;
                break;
            case 'erpAccessToken':
                //企业微信-erp
                $appid  = para("qyWeChatCorpid");
                $secret = para("qyWeChatErpSecret");
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $appid . "&corpsecret=" . $secret;
                break;
            case 'erp3AccessToken':
                //企业微信-erp
                $appid  = para("qyWeChatCorpid");
                $secret = para("qyWeChatErp3Secret");
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $appid . "&corpsecret=" . $secret;
                break;
        }
        $token        = json_decode(curl($url, ""), true);
        $access_token = V($token, 'access_token');
        if (!empty($token['access_token'])) {
            setWeChatToken($paid, $access_token);
        }
    }
    return $access_token;
}

/**
 * 存放$access_token
 *
 * @param        $paid
 * @param string $access_token
 * @return mixed|string
 */
function setWeChatToken($paid, string $access_token = '')
{
    // 判断token ID 是否存在
    $token = para($paid);
    if ($token === str_replace('id', $paid, '参数【id】未找到')) {
        insert([
            'table' => 'para',
            'field' => [
                'paid'    => $paid,
                'paType'  => '参数',
                'paName'  => '企业微信' . $paid,
                'paValue' => '{}',
                'edit'    => '否',
            ],
        ]);
        $token = '';
    }
    if (!empty($access_token)) {
        $time = time() + 7000;
        $list = json_encode(['time' => $time, 'token' => $access_token], 320);
        update(['table' => 'para', 'field' => ['paValue' => $list], 'where' => " paid = '$paid'"]);
        return $access_token;
    } else {
        if (empty($token)) {
            return '';
        } else {
            $token = json_decode($token, true);
            if ($token && $token['time'] < time()) {
                return '';
            } else {
                return V($token, 'token');
            }
        }
    }
}


/*微信消息通知模板
$para = array(
    "openid" => "oCcq2s-Qz0bx8Gy4LgqVm5SgVSSI",//微信openid
    "templateId" => "zp8fxX6nCXI-qTNZciHchfDdzyNXCbr9HincBX3JyYA",//微信模板ID
    "url" => root."control/adBespeakMx?id=bil83220755kD",//跳转路径
    "title" => "你好，有新客户提交了在线预约，请及时跟进",//标题
    "color" => "#ff0000",//颜色
    "keyword1" => "18581286862",//关键词1
    "keyword2" => $time,//关键词2
    "text" => "了解你们的crm"//备注
);
*/
function wxNotice($para): bool|string
{
    $appid  = para("wxAppid");      //微信appid
    $secret = para("wxAppSecret");  // 微信AppSecret
    $json   = curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret", "");
    $token  = json_decode($json, true);
    $url    = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token['access_token']}";
    $json   = array(
        "touser"      => $para['openid'],
        "template_id" => $para['templateId'],
        "url"         => $para['url'],
        "data"        => array(
            "first"    => array(
                "value" => $para['title'],
                "color" => $para['color'],
            ),
            "keyword1" => array(
                "value" => $para['keyword1'],
                "color" => $para['color'],
            ),
            "keyword2" => array(
                "value" => $para['keyword2'],
                "color" => $para['color'],
            ),
            "remark"   => array(
                "value" => $para['text'],
                "color" => $para['color'],
            ),
        ),
    );
    return curl($url, json_encode($json));
}

/*在线预约-推送微信消息*/
function bespeakWxMessage($bespeakId)
{
    $bespeak   = query("bespeak", " id = '$bespeakId' ");
    $time      = date("Y-m-d H:i:s");
    $stidArray = array(
        "sd56afe34", //邹立星
        "Ore126054470Vd", //李敏
        //		"nZc62700718bs",//向雪
        //		"XON79376319fj",//刘小琼
    );
    foreach ($stidArray as $stid) {
        $staff = query("staff", " stid = '$stid' ");
        $para  = array(
            "openid"     => $staff['wxOpenid'], //微信openid
            "templateId" => "zp8fxX6nCXI-qTNZciHchfDdzyNXCbr9HincBX3JyYA", //微信模板ID
            "url"        => root . "m/mStaff/madBespeakMx?id=" . $bespeakId, //跳转路径
            "title"      => "你好，有新客户提交了在线预约，请及时跟进", //标题
            "color"      => "#ff0000", //颜色
            "keyword1"   => kong($bespeak['contactTel']), //关键词1
            "keyword2"   => $time, //关键词2
            "text"       => kong($bespeak['text']), //备注
        );
        wxNotice($para);
    }
}
